package com.starryx.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;


// 统一拦截异常进行处理
@ControllerAdvice       // 此注解会拦截到所有注有 Controller 的控制器
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());     // 拿到日志记录的对象

    @ExceptionHandler(Exception.class)     // 标注此方法是用于异常处理的，参数表示只要是 Exception 级别的异常都是可以处理的
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.error("Request URL : {}, Exception : {}", request.getRequestURL(), e);       // {} 相当于占位符，这样会在控制台输出异常信息

        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){     // 如果存在指定了状态码的异常，就直接抛出，让 spring boot 处理（404）
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;

    }
}
